package com.example.finalproject.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {
    public static final String URL_WEATHER = "http://v1.yiketianqi.com/free/day?appid=68661372&appsecret=IgQtl9UG&unescape=1";
    // 数据请求方法
    public static String doGet(String urlStr, Context context) {
        String result = "";
        HttpURLConnection connection = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;

        // 网络连接
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);
            connection.connect();
        } catch (Exception e) {
            e.printStackTrace();
            new Handler(Looper.getMainLooper()).post(() -> {
                Toast.makeText(context, "网络连接失败", Toast.LENGTH_SHORT).show();
            });
            return result;  // 直接返回，后续不用再处理
        }

        // 读取数据流
        try {
            InputStream inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(inputStreamReader);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            result = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("ToastDebug", "context is: " + context);
            new Handler(Looper.getMainLooper()).post(() -> {
                Toast.makeText(context, "服务器数据读取失败", Toast.LENGTH_SHORT).show();
            });
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    // 获取天气信息
    public static String getWeatherOfCity(String city, Context context) {
        String weatherUrl = URL_WEATHER + "&city=" + city;
        String result = doGet(weatherUrl, context);
        Log.d("result", "---weather result---" + result);
        return result;
    }
}
